package com.sbr.seb.plugin.api;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PluginReader {

	protected static final Logger logger = LoggerFactory.getLogger(PluginReader.class);

	public void checkPluginsJars() {
//		URL pluginsDirectoryURL = getClass().getResource("/plugins");
//		logger.debug("pluginsDirectoryURL = "+pluginsDirectoryURL);
		File pluginDirectory = new File("plugins");
//		try {
//			pluginDirectory = new File(pluginsDirectoryURL.toURI());
//		} catch (URISyntaxException e1) {
//			e1.printStackTrace();
//		}
		for (File jar : pluginDirectory.listFiles()) {
			try {
				JarFile jarFile = new JarFile(jar);
				String className = readManifest(jarFile);
				logger.debug("className = "+className);
				Enumeration<JarEntry> entries = jarFile.entries();
				while (entries.hasMoreElements()) {
					JarEntry entry = entries.nextElement();
					logger.debug("> "+entry.getName());
				}
				checkPlugin(className,jar);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void checkPlugin(String className, File jar) {
		File pluginDirectory = jar;
		URL loadPath = null;
		try {
			loadPath = pluginDirectory.toURI().toURL();
			logger.debug("loadPath = "+loadPath);
		} catch (MalformedURLException e) {
			logger.error("ERROR",e);
		}
		URL[] classUrl = new URL[]{loadPath};

		ClassLoader cl = new URLClassLoader(classUrl);

		try {
			Class<Pluginable> loadedClass = (Class<Pluginable>) cl.loadClass(className);
			Pluginable modInstance = loadedClass.newInstance();
			logger.debug("modInstance = "+modInstance);
			modInstance.start();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}

	}

	public String readManifest(JarFile jarFile) {
		String version = null;
		Manifest manifest = null;
		try {
			manifest = jarFile.getManifest();
		} catch (IOException e) {
			e.printStackTrace();
		}
		version = manifest.getMainAttributes().getValue("Seb-Plugin-ClassName");
		if(version == null) {
			version = "no version information";
		}
		return version;
	}
}
